//
//  SoapService.m
//  SOAP-IOS
//
//  Created by Elliott on 13-7-26.
//  Copyright (c) 2013年 Elliott. All rights reserved.
//

#import "WebRequest.h"


@implementation WebRequest

-(id)initWithPostUrl:(NSString *)url SoapAction:(NSString *)soapAction{
    self=[super init];
    if(self){
        self.PostUrl=url;
        self.SoapAction=soapAction;
    }
    return self;
}


//同步请求
-(void)postSyncForSession:(NSString *)inPutxml AndFuncode:(NSString*)funStr Success:(SuccessBlock)success falure:(FailureBlock)failure
{
    
    
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Header></soap:Header><soap:Body><MuPayInterface xmlns=\"http://tempuri.org/\"><FunCode>%@</FunCode><InputXml>%@</InputXml><RspType>JSON</RspType></MuPayInterface></soap:Body></soap:Envelope>",funStr,inPutxml];
    
    //NSLog(@"%@",webServiceStr);
    
    NSMutableURLRequest *request=[self CreatRequest:webServiceStr];
  
   
    NSURLSession *session = [NSURLSession sharedSession];
    
    
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
            completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                            
  // 处理返回的数据
   NSString *strReturn = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   
                
   //请求失败
    if (error) {
        
    NSLog(@"Session----失败----%@", error.localizedDescription);
        
    failure(error);
   //请求成功
    }else{
        
        NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:@"(?<=OutputXml\\>).*(?=</OutputXml)" options:NSRegularExpressionCaseInsensitive error:nil];
        for (NSTextCheckingResult *checkingResult in [regular matchesInString:strReturn options:0 range:NSMakeRange(0, strReturn.length)]) {
            
            // 得到字典
          NSDictionary *  dict = [NSJSONSerialization JSONObjectWithData:[[strReturn substringWithRange:checkingResult.range] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
            
            success(dict);

            
        }
        
       
    }
                
 }];
    
  [task resume];
    

 
}


-(NSMutableURLRequest *)CreatRequest:(NSString *)postData{
    // 要请求的地址
    NSString *urlString=self.PostUrl;
    // 将地址编码
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    // 实例化NSMutableURLRequest，并进行参数配置
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    
    //超时设置
    if(self.Timeout){
        [request setTimeoutInterval: self.Timeout];
    }else{
        [request setTimeoutInterval: 30];
    }
    if(self.SoapAction){
        [request addValue:self.SoapAction forHTTPHeaderField:@"SOAPAction"];
    }
    if(self.ContentType){
        [request addValue:self.ContentType forHTTPHeaderField:@"Content-Type"];
    }else{
        [request addValue:@"text/xml;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    }
    if(self.UserAgent){
        [request addValue:self.UserAgent forHTTPHeaderField:@"User-Agent"];
    }else{
        [request addValue:@"IOS App (power by elliott)" forHTTPHeaderField:@"User-Agent"];
    }
    if(self.AcceptEncoding){
        [request addValue:self.AcceptEncoding forHTTPHeaderField:@"Accept-Encoding"];
    }
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    return request;
}

@end
